import json
from src.sql import gen_sql
from src.walk import walk
from src.parse import parse
from src.format import format
from pathlib import Path
from zyjkit.print import zprint


if __name__ == "__main__":
    TABLE_NAME = "jin_permission"

    # 清空表
    CLEAR_TABLE = True
    # CLEAR_TABLE = False

    # 需要扫描的目录
    APP_ROOT = "./app"

    # 文件匹配规则
    includes = [
        "admin/controller/*.php",
        "agent/controller/*.php",
        # '**/controller/*.php'
    ]

    # 扫描结果
    permissions = walk(APP_ROOT, parse, include_list=includes)

    # 格式化
    permissions = format(permissions)

    sql = gen_sql(permissions, table_name=TABLE_NAME)

    if CLEAR_TABLE:
        sql = "TRUNCATE TABLE `jin_permission`;\n\n" + sql

    Path("temp").mkdir(parents=True, exist_ok=True)

    Path("temp/permissions.json").write_text(
        json.dumps(permissions, ensure_ascii=False, indent=2), encoding="utf-8"
    )
    Path("temp/permissions.sql").write_text(sql, encoding="utf-8")

    category = {
        "app": 0,
        "controller": 0,
        "method": 0,
        "page": 0,
    }

    for perm in permissions:
        cato = perm["category"]
        category[cato] += 1

    zprint({
            "permissions": len(permissions),
            "sql": len(sql),
            "category": category,
        })


